#include "SoftSerial.h"
#include "GPSSerial.h"


int readingSentence=0;
int pos=0;
char sentence[GPS_SENTENCE_LENGTH]; // create array 49 bytes long to store GPS data (GPRMC IS 48 bytes + 1 for 0 to signify end of line
unsigned char* GMCPoint;

void GPSparse()
{
  byte NMEACode[7]; // create buffer to store NMEA Code to verify GPRMC is being read
  int i;
  while(SoftSerial.available()) // while there are bytes available to be read in serial port (stays in loop)
  {
    
    if(readingSentence==1) // if GPRMC has been identified enter this loop
    {
      if(SoftSerial.peek()!='*') // enter loop unless end character has been identified
        sentence[pos++]=SoftSerial.read(); // add bytes to sentence incrementally
      else
      {
        sentence[pos]=0; // having reached the end of the sentence (*), add value 0 (signifies end line)
        readingSentence=0; // reset readingSentence to check for GPRMC again
        pos=0; // reset pos to zero so that it starts writing at beginning of sentence for next line of data 
        for (i=0; i<GPS_SENTENCE_LENGTH; i++)
         GMCPoint[i]=sentence[i];
        SoftSerial.clear(); //THIS NEEDS TO BE DEFINED IN SoftSerial
      }      
    }  
    else if(SoftSerial.peek()=='$') // if readingSentence=0, check to see if at beginning of sentence (signified by $) (peek ensures data stored in buffer is not erased)
    {
      if(SoftSerial.available()>7) // make sure 7 bytes are available to be read (NMEA Code)
      {
        for (i=0; i<7; i++)
          NMEACode[i]=SoftSerial.read(); // store NMEA Code at beginning of line
          
        if(memcmp(NMEACode,"$GPRMC,",sizeof(NMEACode))==0) // check if it is correct NMEA code
          readingSentence=1; // set readingSentence to 1 if it is correct NMEA code
      }
      else
        break;
     }
    else
      SoftSerial.read();
  }  
}


void initialiseGPS(unsigned char* sentenceOut)
{
  SoftSerial.begin(9600);
  GMCPoint=sentenceOut;
}

